<template>
  <a-modal
    :title="title"
    :width="1000"
    :visible="visible"
    :maskClosable="false"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
  >
    <a-spin :spinning="formLoading">
      <a-form :form="form">
        <a-form-item v-show="false">
          <a-input v-decorator="['id']"/>
        </a-form-item>

        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="菜单名称" :labelCol="labelCol" :wrapperCol="wrapperCol" hasFeedback>
              <a-input
                placeholder="请输入菜单名称"
                v-decorator="[
                                    'title',
                                    { rules: [{ required: true, min: 1, message: '请输入菜单名称！' }] },
                                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              style="width: 100%"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="菜单编号"
              hasFeedback
            >
              <a-input
                placeholder="请输入菜单编号"
                v-decorator="[
                                    'name',
                                    { rules: [{ required: true, min: 1, message: '请输入菜单编号！' }] },
                                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :md="12" :sm="24"></a-col>
          <a-col :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="菜单类型">
              <a-radio-group
                v-decorator="['type', { rules: [{ required: true, message: '请选择菜单层级！' }] }]"
              >
                <a-radio
                  v-for="(item, index) in typeData"
                  :key="index"
                  :value="item.code"
                  @click="meneTypeFunc(item.code)"
                >{{ item.value }}
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <div v-show="parentShow">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="父级菜单" has-feedback>
                <a-tree-select
                  v-decorator="[
                                        'parent',
                                        { rules: [{ required: false, message: '请选择父级菜单！' }] },
                                    ]"
                  style="width: 100%"
                  :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
                  :treeData="menuTreeData"
                  placeholder="请选择父级菜单"
                  treeDefaultExpandAll
                >
                  <span slot="title" slot-scope="{ id }">{{ id }} </span>
                </a-tree-select>
              </a-form-item>
            </div>
            <div v-show="redirectShow">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
                                <span slot="label">
                                    <a-tooltip
                                      title="如需打开首页加载此目录下菜单，请填写加载菜单路由，设为首页后其他设置的主页将被替代"
                                    >
                                        <a-icon type="question-circle-o"/> </a-tooltip
                                    >&nbsp; 重定向
                                </span>
                <a-input prop="redirect" placeholder="请输入重定向地址" v-decorator="['redirect']"/>
              </a-form-item>
            </div>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <span slot="label">
                                <a-tooltip title="按钮：无，菜单：内链、外链、组件">
                                    <a-icon type="question-circle-o"/> </a-tooltip
                                >&nbsp; 打开方式
                            </span>
              <a-radio-group
                :disabled="openTypeDisabled"
                v-decorator="['openType', { rules: [{ required: true, message: '请选择打开方式！' }] }]"
              >
                <a-radio
                  v-for="(item, index) in openTypeData"
                  :key="index"
                  :value="item.code"
                  @click="meneOpenTypeFunc(item.code)"
                >{{ item.value }}
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>

        <a-divider/>

        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <div v-show="componentShow">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" hasFeedback>
                                <span slot="label">
                                    <a-tooltip
                                      title="前端vue组件 views文件夹下路径，例：system/menu/index。注：目录级填写：RouteView(不带面包屑)，PageView(带面包屑)，菜单级内链打开http链接填写：Iframe"
                                    >
                                        <a-icon type="question-circle-o"/> </a-tooltip
                                    >&nbsp; 前端组件
                                </span>
                <a-input
                  placeholder="请输入前端组件"
                  :disabled="componentDisabled"
                  prop="component"
                  v-decorator="[
                                        'component',
                                        { rules: [{ required: componentRequired, message: '请输入前端组件' }] },
                                    ]"
                />
                <!-- ,{rules: [{required: componentRequired, min: 1, message: '请输入前端组件！'}]}  -->
              </a-form-item>
            </div>
          </a-col>
          <a-col :md="12" :sm="24">
            <div v-show="pathShow">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" hasFeedback>
                                <span slot="label">
                                    <a-tooltip title="浏览器显示的URL，例：/menu，对应打开页面为菜单页面">
                                        <a-icon type="question-circle-o"/> </a-tooltip
                                    >&nbsp; 路由地址
                                </span>
                <a-input
                  placeholder="请输入路由"
                  v-decorator="[
                                        'path',
                                        { rules: [{ required: pathRequired, message: '请输入路由！' }] },
                                    ]"
                />
              </a-form-item>
            </div>

            <div v-show="permissionShow">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="权限标识">
                <a-input
                  placeholder="请输入权限标识"
                  v-decorator="[
                                        'permission',
                                        { rules: [{ required: permissionRequired, message: '请输入权限标识！' }] },
                                    ]"
                />
              </a-form-item>
            </div>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序">
              <a-input-number
                style="width: 100%"
                v-decorator="['sort', { initialValue: 100 }]"
                :min="1"
                :max="1000"
              />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <div v-show="iconShow">
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="图标">
                <a-input placeholder="请选择图标" disabled="disabled" v-decorator="['icon']">
                  <a-icon slot="addonAfter" @click="openIconSele()" type="setting"/>
                </a-input>
              </a-form-item>
            </div>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否可见">
              <a-switch
                id="show"
                checkedChildren="是"
                unCheckedChildren="否"
                v-decorator="['show', { valuePropName: 'checked' }]"
              /><!-- defaultChecked -->
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <a-modal
      :width="850"
      :visible="visibleIcon"
      @cancel="handleCancelIcon"
      footer=""
      :mask="false"
      :closable="false"
      :destroyOnClose="true"
    >
      <icon-selector v-model="currentSelectedIcon" @change="handleIconChange"/>
    </a-modal>
  </a-modal>
</template>

<script>
  import * as api from '@/api/system/menuManage'
  import config from '@/config/dict'
  import IconSelector from '@/components/IconSelector'

  const openTypeData = [
    {
      code: 2,
      value: '外链 '
    },
    {
      code: 1,
      value: '组件'
    },
    {
      code: 0,
      value: '无'
    }
  ]
  const typeData = [
    {
      code: 1,
      value: '菜单'
    },
    {
      code: 0,
      value: '目录'
    }
  ]

  export default {
    name: 'sForm',
    components: { IconSelector },

    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        visibleIcon: false,
        visible: false,
        title: '',
        appData: [],
        menuTreeData: [],
        redirectShow: true,
        componentShow: true,
        componentDisabled: false,
        componentRequired: true,
        pathRequired: true,
        pathShow: true,
        iconShow: true,
        openTypeShow: true,
        parentShow: true,
        // 图标组件
        currentSelectedIcon: 'pause-circle',
        typeData,
        formLoading: true,
        openTypeData,
        openTypeDisabled: false,
        openTypeDefault: [],
        openType: '',
        linkRequired: true,
        linkDisabled: false,
        permissionRequired: false,
        permissionShow: false,
        type: '',
        message: {},
        form: this.$form.createForm(this)
      }
    },

    methods: {
      // 打开页面初始化
      open(record) {
        this.visible = true
        this.getMenuTree()
        // 编辑
        if (record) {
          this.title = '编辑菜单'
          this.currentSelectedIcon = record.icon
          this.form.getFieldDecorator('type', { valuePropName: 'checked', initialValue: record.type })
          this.meneTypeFunc(record.type, record.target)

          this.form.getFieldDecorator('icon', { initialValue: record.icon })
          this.form.getFieldDecorator('show', { initialValue: record.show })

          this.$nextTick(() => {
            setTimeout(() => {
              this.setMenuItem(record)
            }, 100)
          })
          // 新增
        } else {
          this.title = '新增菜单'
          this.currentSelectedIcon = record
          // 默认选中菜单项，并初始化
          this.form.getFieldDecorator('type', { valuePropName: 'checked', initialValue: 1 })
          this.meneTypeFunc(1)

          // 默认选中的单选框
          this.form.getFieldDecorator('show', { initialValue: true })
        }
        this.formLoading = false
      },

      setMenuItem(record) {
        this.form.setFieldsValue({
          id: record.id,
          title: record.title,
          name: record.name,
          redirect: record.redirect,
          permission: record.permission,
          component: record.component,
          path: record.path,
          sort: record.sort
        })
        this.form.getFieldDecorator('parent', { initialValue: record.parent })
      },
      // 获取的所有菜单目录
      getMenuTree() {
        api.getList().then((res) => {
          if (!res.error) {
            this.form.resetFields(parent, [])
            this.menuTreeData = [
              {
                id: 0,
                parent: '0',
                title: '顶级',
                value: '0',
                children: res.data
              }
            ]
          } else {
            this.$message.warning(res.error)
          }
        })
      },
      /**
       * 选择菜单类型执行初始化表单变量
       */
      meneTypeFunc(type, openType) {
        this.type = type
        // 当类型为菜单或者目录时
        if (type === 0 || type === 1) {
          // 内外链地址显示，给空值
          // this.form.resetFields(`link`, [])
          // 图标选择显示
          this.iconShow = true
          // 路由必填，设置空值，并显示
          this.pathShow = true
          this.pathRequired = true
          this.form.getFieldDecorator('path', { initialValue: '' })
          // 打开方式设置为组件 ，禁用选择方式
          this.openType = 1
          this.form.getFieldDecorator('openType', { initialValue: 1 })
          this.openTypeDisabled = false
          this.permissionRequired = false
          this.permissionShow = false
          this.form.getFieldDecorator('permission', { initialValue: '' })
        }
        if (type === 0) {
          // 重定向展示，并给空
          this.redirectShow = true
          this.form.resetFields(`redirect`, [])
          // 组件默认为显示，设置可输入，给默认组件 PageView，验证必填
          this.componentShow = true
          this.componentDisabled = false
          this.form.getFieldDecorator('component', { initialValue: 'PageView' })
          this.componentRequired = true
          // 父级初始化顶级，并将其隐藏
          // this.form.getFieldDecorator('parent', { initialValue: '0' })
          this.parentShow = false
        } else {
          if (type === 1) {
            // 组件可以手输，取消值
            this.componentDisabled = false
            this.form.getFieldDecorator('component', { initialValue: '' })
          }
          // 重定向输入隐藏，并给空值
          this.redirectShow = false
          this.form.getFieldDecorator('redirect', { initialValue: '' })
          // 父级选择放开
          this.parentShow = true
        }
        // 当类型为按钮时
        if (type === 2) {
          // 组件设置不填，不可输入，并给空（手输的跟设置的）
          this.componentRequired = false
          this.componentDisabled = true
          this.form.resetFields(`component`, [])
          this.form.getFieldDecorator('component', { initialValue: '' })
          // 路由选填，设置空值，并隐藏
          this.pathRequired = false
          this.form.getFieldDecorator('path', { initialValue: '' })
          this.pathShow = false
          this.form.getFieldDecorator('link', { initialValue: '' })
          // 图标选择隐藏,并给空
          this.iconShow = false
          this.form.getFieldDecorator('icon', { initialValue: '' })
          // 打开方式设置为无 ，禁用选择方式
          this.openType = 0
          this.form.getFieldDecorator('openType', { initialValue: this.openType })
          this.openTypeDisabled = true
          // 取消icon
          this.form.getFieldDecorator('icon', { initialValue: '' })
          this.permissionRequired = true
          this.permissionShow = true
        }
        if (openType) {
          this.meneOpenTypeFunc(openType)
        } else {
          this.meneOpenTypeFunc(this.openType)
        }
      },

      /**
       * 选择打开方式执行方法
       */
      meneOpenTypeFunc(openType) {
        this.form.resetFields(`openType`, openType)
        if (openType === 2) {
          this.componentRequired = false
          this.componentDisabled = true
          this.form.resetFields(`component`, [])
          this.form.getFieldDecorator('component', { initialValue: '' })
        }
        // 另起一个分支
        this.componentRequired = true
        if (this.type === 1 || this.type === 2) {
          this.form.getFieldDecorator('component', { initialValue: '' })
        } else {
          this.form.resetFields(`component`, [])
          this.form.getFieldDecorator('component', { initialValue: 'PageView' })
        }

        if (this.type === 2) {
          if (openType === 0) {
            this.componentRequired = false
            this.pathRequired = false
          }
        }
      },

      openIconSele() {
        this.visibleIcon = true
      },
      handleIconChange(icon) {
        this.form.getFieldDecorator('icon', { initialValue: icon })
        this.visibleIcon = false
      },
      handleCancelIcon() {
        this.visibleIcon = false
      },
      handleSubmit() {
        const {
          form: { validateFields }
        } = this
        validateFields((errors, values) => {
          if (!errors) {
            if (values.parent === "0") {
              values.parent = null
            }
            if (values.id) {
              this.message = config.msgDict[1]
              api.updateObj(values)
                .then((res) => {
                  this._handle_response(res, values)
                })
            } else {
              this.message = config.msgDict[0]
              api.addObj(values)
                .then((res) => {
                  this._handle_response(res, values)
                })
            }
          }
        })
      },
      // 处理返回消息
      _handle_response(res, values) {
        if (res.success) {
          this.$message.success(this.message['success'])
          this.handleCancel()
          this.$emit('ok', values)
        } else {
          this.$message.error(this.message['failed'] + res.message)
        }
      },
      handleCancel() {
        this.form.resetFields()
        this.visible = false
      }
    }
  }
</script>
